<?php

class ItemService extends AbstractService
{

    /**
     * @var ItemService
     */
    private static $instance;

    /**
     * Get the instance of ItemService.
     *
     * @return ItemService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new ItemService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    protected function __construct()
    {
        parent::__construct();
    }

    /**
     * 处理用户创建时的逻辑
     *
     * @param int $userId
     * @param ModuleItemVoList $itemList default null
     * @return void
     */
    public function handleCreate($userId, $itemList = null)
    {
        $initItemSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME, GameConst::DEFAULT_GAME_SETTING_KEY, true);
        foreach ($initItemSetting['initItem'] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true, true, array(), $itemList);
        }
        SzPersister::get()->setVoList($itemList);
    }

    /**
     * 处理用户登录时的逻辑
     *
     * @param int $userId
     * @return void
     */
    public function handleLogin($userId)
    {
        // do nothing
    }

    /**
     * 提供当前 service 数据
     *
     * @param int $userId
     * @param boolean $visitMode default false
     * @return array(ModuleItemVoList, ItemLogsVoList, array)
     */
    public function info($userId, $visitMode = false)
    {
        $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
        $itemLogsList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ITEM_LOGS);
        $buildingItems = $this->getBuildingItems($userId);

        return array(
            $itemList,
            $itemLogsList,
            $buildingItems
        );
    }

    /**
     * 将道具定义id拆分成，道具小类型 和 道具等级 和 道具小类型下的序号
     *
     * @param $itemDefId
     * @return array
     * <pre>
     *     array($type, $level, $subId)
     * </pre>
     */
    public function parseItemDefId($itemDefId)
    {
        $itemDefId = sprintf('%1$08d', $itemDefId); // 补足8位，因为我们定义的itemDefId格式最长为6位
        $category = (int)substr($itemDefId, 0, 2); // 可能以0开头，转整形，去0
        $type = substr($itemDefId, 2, 2);
        $level = substr($itemDefId, 4, 2);
        $subId = substr($itemDefId, 6, 2);

        return array($category, $type, $level, $subId);
    }

    /**
     * 判断道具是否属于永久道具
     *
     * @param int | array $config
     * @return boolean
     */
    public function isPermanently($config)
    {
        if (!is_array($config)) { // config is: int type itemDefId
            $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $config, true);
        } else { // config is: $itemSetting itself
            $itemSetting = $config;
        }

        switch ($itemSetting['category']) {
            case GameConst::ITEM_CATEGORY_INDOOR_DECOR:
            case GameConst::ITEM_CATEGORY_PRODUCE_MACHINE:
            case GameConst::ITEM_CATEGORY_WAREHOUSE:
            case GameConst::ITEM_CATEGORY_OUTDOOR_DECOR:
            case GameConst::ITEM_CATEGORY_TREE:
            case GameConst::ITEM_CATEGORY_FLOWER_TABLE:
            case GameConst::ITEM_CATEGORY_SPECIAL:
            case GameConst::ITEM_CATEGORY_WALL_BRICK:
            case GameConst::ITEM_CATEGORY_SOIL:
                return true;
            default:
                return false;
        }
    }

    /**
     * 道具处理（增，减）统一逻辑
     * 入口在 handleEntity 中的业务逻辑，涉及到道具相关的，会再次回到 ItemService::processItems 里
     * 如果有需要 persistence 的话，可以在 handleEntity 的参数 $persist 里给 true
     *
     * @see GameService::handleEntity
     * @param int $userId
     * @param array $items
     * <pre>
     * array(
     *     itemDefId => count,
     *     ...
     * )
     * </pre>
     * @param ModuleItemVoList $itemList default null
     * @param boolean $allowExceedLimit default false
     * @param int $commodityValue default 0
     * @param boolean $isNeedLevel default true
     * <pre>
     * 当该参数为0
     *      1. item中count参数为正数，增加的道具必定是免费道具，不需要处理价值流转
     *      2. item中count参数为负数，扣除的道具可能为付费道具，根据付费道具数量的扣除量，扣除价值后，并在返回结果中加入扣除的价值，与扣除的付费道具量
     *      3. 判断$logCommodityConsume，如果为true，则记为价值消耗
     * 当该参数小于0
     *      1. 不可能出现的情况，将该参数调整为0
     * 当该参数大于0
     *      1. item中count参数为正数，增加的道具必定为道具代币，并增加外部传入的价值
     *      2. item中count参数为负数，不可能出现的情况，如果出现，该参数调整为0
     *      3. 判断$logCommodityConsume，如果为true，则修改为false, 记为价值流入，并在外部进行日志采集c
     * </pre>
     * @throws SzException
     * @return array(ModuleItemVoList, int, array($entityId => array($count, $commodityValue), ...))
     */
    public function processItems($userId, $items, $itemList = null, $allowExceedLimit = false, $commodityValue = 0, $isNeedLevel = true)
    {
        $allowExceedLimit = true;
        if (is_null($itemList)) {
            $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
        }

        // 计算item中数量为正值的单种道具平均价值
        $addItemDefIdCount = 0;
        foreach ($items as $count) {
            if ($count > 0) {
                $addItemDefIdCount++;
            }
        }
        $commodityValue = ($commodityValue > 0 && $addItemDefIdCount > 0) ? $commodityValue / $addItemDefIdCount : 0; // 单种道具平均价值

        // 如果处理多道具，则需要将价值平均分配到每个道具身上
        $commodityItemData = array();
        $commodityAmountValue = 0;
        foreach ($items as $itemDefId => $count) {
            if ($count == 0) {
                continue;
            }

            // 修改前的付费道具数量与价值
            list($originalPurchasedCount, $originCommodityValue) = $itemList->getPurchasedCountAndCommodityValueByDefId($itemDefId);

            if ($count < 0) {
                // 道具扣除
                $logCommodityConsume = true;
                //验证是否物品可使用
//                if ($isNeedLevel && !CollectionService::get()->isUnlock($userId, $itemDefId)) {
//                    throw new SzException(20044, $itemDefId);
//                }
                $count = WarehouseService::get()->processWarehouse($userId, $itemDefId, $count);
                $itemList = ModuleItem::get()->reduceItemCountByDefId($userId, $itemDefId, abs($count), $itemList, null);

                if ($itemDefId == 19000004){
                    /**
                     * @var ModuleItemVoList $tempList
                     */
                    //获取好评券数量
                    $tempList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
                    $ownCount = $tempList->getItemDefCount($itemDefId);
                    //特殊处理好评券消耗后的总数
                    StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                        'clientData' => array(
                            'tid' => 'Module:resource|action:getTotal|',
                            'item' => 19000004,
                            'value2' => $ownCount,
                        )
                    ));
                }
            } else {
                // 增加物品通用逻辑：不允许超出上限
                $logCommodityConsume = false;

                // 道具获得
                if ($allowExceedLimit) {
                    // 允许超出上限
                    $count = WarehouseService::get()->processWarehouse($userId, $itemDefId, $count, $allowExceedLimit);
                    $itemList = ModuleItem::get()->addItemCount($userId, $count, $itemList, $itemDefId, null, array(), $allowExceedLimit, true, $commodityValue);
                } else {
                    // 拥有数量未超出上限 超出数量的情况什么都不做
                    $ownCount = $itemList->getItemDefCount($itemDefId);
                    $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $itemDefId, true);
                    if ($ownCount < $itemSetting['ownLimit']) {
                        // 增加后会超出上限
                        if (($ownCount + $count) > $itemSetting['ownLimit']) {
                            $count = $itemSetting['ownLimit'] - $itemList->getItemDefCount($itemDefId);
                        }
                        // 可能超过仓库上限，所以道具被丢弃，为了不被道具模块报错，此处增加判断最终道具增加数量不为0
                        $count = WarehouseService::get()->processWarehouse($userId, $itemDefId, $count, $allowExceedLimit);
                        if ($count > 0) {
                            $itemList = ModuleItem::get()->addItemCount($userId, $count, $itemList, $itemDefId, null, array(), $allowExceedLimit, false, $commodityValue);
                        }
                    }
                }
                if ($count > 0 && isset($itemSetting['unlockFlowerId']) && $itemSetting['unlockFlowerId'] != -1) {
                    SeedService::get()->unlockSeed($userId, $itemSetting['unlockFlowerId']);
                }
            }
            // 道具价值流转
            list($nowPurchasedCount, $nowCommodityValue) = $itemList->getPurchasedCountAndCommodityValueByDefId($itemDefId);

            // 付费代币数量变更与价值变更
            $changePurchasedCount = $originalPurchasedCount - $nowPurchasedCount;
            $changedCommodityValue = $originCommodityValue - $nowCommodityValue;

            $buildEntityId = EntityService::get()->buildEntityId(GameConst::ENTITY_ACTION_GET, GameConst::ENTITY_TYPE_ITEM, $itemDefId);
            $commodityItemData[$buildEntityId] = array($changedCommodityValue, $changePurchasedCount);
            if ($logCommodityConsume && $changedCommodityValue != 0) {
                // 任务进度计数：价值消耗
                StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_FINANCE_CASH, array(
                    'clientData' => array(
                        'tid' => $buildEntityId . ':' . abs($changePurchasedCount) . '|',
                        'item' => 1,
                        'value' => abs($changedCommodityValue),
                    )
                ));
            }
            $commodityAmountValue += $changedCommodityValue;
        }
        return array(
            $itemList,
            $commodityAmountValue,
            $commodityItemData
        );
    }

    /**
     * 记录道具购买次数
     *
     * @param int $userId
     * @param int $itemDefId
     * @param int $count
     * @param ItemLogsVoList $itemLogsList
     * @return void
     */
    public function logItemBuyCount($userId, $itemDefId, $count, $itemLogsList = null)
    {
        if ($itemLogsList == null) {
            $itemLogsList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ITEM_LOGS);
        }

        /**
         * @var ItemLogsVo $itemLogs
         */
        $itemLogs = $itemLogsList->getElement($itemDefId, false);

        if (!$itemLogs) {
            $itemLogs = new ItemLogsVo($userId, $itemDefId, $count);
            $itemLogsList->addElement($itemLogs);
            $itemLogsList->setElement($itemDefId, $itemLogs);
        } else {
            $itemLogs->updateCount($count);
            $itemLogsList->updateElement($itemDefId, $itemLogs);
        }

        SzPersister::get()->setVoList($itemLogsList);
    }

    /**
     * 获取道具购买次数
     *
     * @param int $userId
     * @param int $itemDefId
     * @param ItemLogsVoList $itemLogsList
     * @return int
     */
    public function getItemBuyCount($userId, $itemDefId, $itemLogsList = null)
    {
        if ($itemLogsList == null) {
            $itemLogsList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ITEM_LOGS);
        }

        /**
         * @var ItemLogsVo $itemLogs
         */
        $itemLogs = $itemLogsList->getElement($itemDefId, false);

        return (!$itemLogs) ? 0 : $itemLogs->getCount();
    }

    /**
     * 获取建筑背包
     *
     * @param int $userId
     * @return array
     */
    public function getBuildingItems($userId)
    {
        $buildingSettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_BUILDING, null, true);

        /**
         * @var ModuleItemVoList $itemList
         * @var ModuleItemVo $item
         */
        $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);

        /**
         * @var array $buildingItems
         * <pre>
         * [
         *  {
         *      'itemDefId' => $itemDefId
         *      'count' => $count
         *      'updateTime' => $updateTime
         *  }
         *  , ...
         * ]
         * </pre>
         */
        $buildingItems = array();
        foreach ($itemList->getList() as $itemDefId => $items) {
            // 不是建筑道具
            if (!SzUtility::checkArrayKey($itemDefId, $buildingSettings)) {
                continue;
            }
            $count = 0;
            $updateTime = 0;
            foreach ($items as $item) {
                $count += $item->getCount();
                $updateTime = $item->getUpdateTime();
            }
            // 道具数量不足
            if ($count <= 0) {
                continue;
            }
            $buildingItems[] = array(
                'itemDefId' => $itemDefId,
                'count' => $count,
                'updateTime' => $updateTime
            );
        }

        array_multisort(array_column($buildingItems, 'updateTime'), SORT_DESC, $buildingItems);

        return $buildingItems;
    }

    /**
     * 购买道具
     *
     * @param int $userId
     * @param int $itemDefId
     * @param int $count
     * @param boolean $addIntoPackage default true
     * @throws 30107
     * @return boolean
     */
    public function buy($userId, $itemDefId, $count, $addIntoPackage = true)
    {
        $reqTime = GameService::get()->getReqTime();

        $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $itemDefId, true);
        $storeSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEMS_STORE, $itemSetting['itemDefId'], true);

        // prepare params
        $onShelf = SzTime::getTimestamp($storeSetting['onShelf']);
        $offShelf = SzTime::getTimestamp($storeSetting['offShelf']);

        // 上下架验证
        if (($storeSetting['onShelf'] != -1 && $onShelf && $reqTime < $onShelf)
            || ($storeSetting['offShelf'] != -1 && $offShelf && $reqTime > $offShelf)
        ) {
            throw new SzException(30106, $itemDefId, ModuleItemConst::MODULE_NAME);
        }

        // 等级验证
        if ($storeSetting['level'] > 1) {
            $userLevel = UserService::get()->getUserLevel($userId);
            if ($userLevel < $storeSetting['level']) {
                throw new SzException(30107, $itemDefId, ModuleItemConst::MODULE_NAME);
            }
        }

        // 验证打折日期
        $discountStart = SzTime::getTimestamp($storeSetting['discountStart']);
        $discountEnd = SzTime::getTimestamp($storeSetting['discountEnd']);
        $discountBase = 1;
        if (($storeSetting['discountStart'] != -1 && $reqTime >= $discountStart)
            && ($storeSetting['discountEnd'] != -1 && $reqTime <= $discountEnd)
        ) {
            $discountBase = $storeSetting['discount'];
        }

        // 购买记录
        $priceId = $storeSetting['moneyType'];
        $priceCount = $storeSetting['priceBase'] + $storeSetting['priceRiseRate'] * ItemService::get()->getItemBuyCount($userId, $itemDefId);
        $priceCount = intval($priceCount * $count * $discountBase);

        // 扣除费用
        list(, $commodityValue) = GameService::get()->handleEntity($userId, $priceId, $priceCount, true, false, array(), false);
        $commodityValue = abs($commodityValue);

        // 增加道具，可破上限
        $buyCount = $count * $storeSetting['count'];
        if ($addIntoPackage) {
            GameService::get()->handleEntityViaBuild(
                $userId,
                GameConst::ENTITY_ACTION_GET, $itemSetting['moduleId'], $itemDefId,
                $buyCount, true, true, array(),
                true, $commodityValue
            );
        }

        // 记录购买次数
        ItemService::get()->logItemBuyCount($userId, $itemDefId, $count);

        // 更新任务计数，建筑收集
        if (in_array($itemSetting['category'], json_decode(GameConst::ENTITY_TYPE_BUILDING_CAT, true))) {
            MissionService::get()->progress($userId, GameConst::ENTITY_ACTION_GAIN_ANY_BUILDING, GameConst::ENTITY_TYPE_ITEM, $itemDefId, 1);
            MissionService::get()->progress($userId, GameConst::ENTITY_ACTION_GAIN_TYPE_BUILDING, GameConst::ENTITY_TYPE_ITEM, $itemDefId, BuildingService::get()->getBuildingCount($userId, $itemDefId) + 1);
        }

        // 数据采集：商店购买物品
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:shop|action:buy|',
                'item' => $itemDefId,
                'value' => 1
            )
        ));

        // 数据采集: 商店购买消耗
        if ($priceId == GameConst::ENTITY_ACTION_CONSUME_MONEY) {
            StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
                'clientData' => array(
                    'item' => 'shop_buy_' . $itemDefId,
                    'value' => abs($priceCount)
                )
            ));
        } else {
            StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_INPUT, array(
                'clientData' => array(
                    'tid' => $priceId . ':' . abs($priceCount) . '|',
                    'item' => 'shop_buy_' . $itemDefId
                )
            ));
        }

        // 数据采集：商店购买产出
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $itemDefId . ':' . $buyCount . '|',
                'item' => 'shop_buy'
            )
        ));

        // 并且非永久道具才进行数据记录
        if ($commodityValue > 0) {
            if (!$addIntoPackage || $itemSetting['moduleId'] != 10) {
                // 价值消耗
                StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_FINANCE_CASH, array(
                    'clientData' => array(
                        'tid' => $priceId . ':' . abs($priceCount) . '|',
                        'item' => 1,
                        'value' => abs($commodityValue),
                    )
                ));
            } else {
                // 价值流转
                $financeEntityId = EntityService::get()->buildEntityId(GameConst::ENTITY_ACTION_GET, GameConst::ENTITY_TYPE_ITEM, $itemSetting['itemDefId']);
                StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_FINANCE_TRANS, array(
                    'clientData' => array(
                        'tid' => $financeEntityId . ':' . abs($commodityValue) . '|',
                        'item' => $priceId,
                        'value' => abs($priceCount),
                        'value2' => $commodityValue,
                    )
                ));
            }
        }
        return true;
    }

    /**
     * 快速购买道具
     *
     * @param int $userId
     * @param int $itemDefId
     * @param int $count
     * @param int $reasonId
     * @param boolean $addIntoPackage default true
     * @throws 30107
     * @return boolean
     */
    public function quickBuy($userId, $itemDefId, $count, $reasonId, $addIntoPackage = true)
    {
        $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $itemDefId, true);

        if ($itemSetting['quickBuyCost'] <= 0) {
            throw new SzException(30106, $itemDefId, ModuleItemConst::MODULE_NAME);
        }

        // 购买记录
        $priceId = GameConst::ENTITY_ACTION_CONSUME_MONEY;
        $priceCount = ceil($itemSetting['quickBuyCost'] * $count);

        // 扣除费用
        list(, $commodityValue) = GameService::get()->handleEntity($userId, $priceId, $priceCount, true, false, array(), false);
        CommonFunctionService::get()->reportResourceUseDetails(99999993,$userId,0,$priceId.':'.$priceCount.'|','quickBuy');//消耗资源上报
        $commodityValue = abs($commodityValue);

        if ($addIntoPackage) {
            // 购买道具，可破上限
            GameService::get()->handleEntityViaBuild(
                $userId,
                GameConst::ENTITY_ACTION_GET, $itemSetting['moduleId'], $itemDefId,
                $count, true, true, array(),
                true, $commodityValue
            );
            CommonFunctionService::get()->reportResourceUseDetails(99999993,$userId,1,GameConst::ENTITY_ACTION_GET.$itemSetting['moduleId'].$itemDefId.':'.$count.'|','quickBuy');//获得资源上报
        }

        // 数据采集:材料补全
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:item|action:buy|',
                'item' => ($reasonId != 0) ? $reasonId . '_' . $itemDefId : $itemDefId,
                'value' => 1
            )
        ));

        // 数据采集:粉刷材料补全时消耗钻石
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'item' => 'item_buy_' . (($reasonId != 0) ? $reasonId . '_' . $itemDefId : $itemDefId),
                'value' => abs($priceCount)
            )
        ));

        // 数据采集:材料补全产出
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $itemDefId . ':' . $count . '|',
                'item' => ($reasonId != 0) ? 'item_buy_' . $reasonId : 'item_buy'
            )
        ));

        // 价值大于0，价值流转
        if ($commodityValue > 0) {
            if ($itemSetting['moduleId'] != 1) {
                // 价值消耗
                StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_FINANCE_CASH, array(
                    'clientData' => array(
                        'tid' => $priceId . ':' . abs($priceCount) . '|',
                        'item' => 1,
                        'value' => abs($commodityValue),
                    )
                ));
            } else {
                // 任务进度计数：价值流转
                $financeEntityId = EntityService::get()->buildEntityId(GameConst::ENTITY_ACTION_GET, GameConst::ENTITY_TYPE_ITEM, $itemSetting['itemDefId']);
                StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_FINANCE_TRANS, array(
                    'clientData' => array(
                        'tid' => $financeEntityId . ':' . abs($commodityValue) . '|',
                        'item' => $priceId,
                        'value' => abs($priceCount),
                        'value2' => $commodityValue,
                    )
                ));
            }
        }
        return true;
    }

    /**
     * 道具出售
     *
     * @param int $userId
     * @param int $itemDefId
     * @param int $count
     * @param boolean $sellItemInPackage default true
     * @return boolean
     */
    public function sell($userId, $itemDefId, $count, $sellItemInPackage = true)
    {
        $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $itemDefId, true);

        /* @var ModuleItemVoList $itemList */
        $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
        list($itemList, $recycleId, $recycleCount) = ModuleItem::get()->recycleItem($userId, $count, $itemList, $itemSetting, $sellItemInPackage);
        SzPersister::get()->setVoList($itemList);

        // 获得道具出售后的资源
        GameService::get()->handleEntity($userId, $recycleId, $recycleCount, true);
        CommonFunctionService::get()->reportResourceUseDetails(99999992,$userId,1,$recycleId.':'.$recycleCount.'|','sell');//获得资源上报

        // 数据采集：物品出售
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:item|action:sell|',
                'item' => $itemDefId,
                'value' => 1
            )
        ));

        // 数据采集: 物品出售-消耗
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_INPUT, array(
            'clientData' => array(
                'tid' => $itemDefId . ':' . abs($count) . '|',
                'item' => 'item_sell_' . $itemDefId
            )
        ));

        // 数据采集：物品出售-产出
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $recycleId . ':' . $recycleCount . '|',
                'item' => 'shop_buy'
            )
        ));

        return true;
    }

    /**
     * 钻石买金币
     *
     * @param $userId
     * @param $produceId
     * @return bool
     */
    public function buyTokenUseDiamond($userId, $produceId)
    {
        $goldConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_GOLD, $produceId, true);
        list(, $commodityValue) = GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $goldConfig["price"], true, true, array(), false);
        CommonFunctionService::get()->reportResourceUseDetails(99999991,$userId,0,GameConst::ENTITY_ACTION_CONSUME_MONEY.':'.$goldConfig["price"].'|','buyTokenUseDiamond');//消耗资源上报
        $commodityValue = abs($commodityValue);

        GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_GET_TOKEN, $goldConfig["count"], true, true, array(), true, $commodityValue);
        CommonFunctionService::get()->reportResourceUseDetails(99999991,$userId,1,GameConst::ENTITY_ACTION_GET_TOKEN.':'.$goldConfig["count"].'|','buyTokenUseDiamond');//获得资源上报

        //数据采集: 钻石兑换金币
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:Exchange|action:diamond|',
                'item' => $produceId,
                'value' => abs($goldConfig["price"])
            )
        ));

        //数据采集: 钻石兑换金币消耗钻石数
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'tid' => '',
                'item' => 'Exchange&diamond',
                'value' => abs($goldConfig["price"])
            )
        ));

        //数据采集: 钻石兑换金币产出
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => GameConst::ENTITY_ACTION_GET_TOKEN . ':' . $goldConfig['count'] . '|',
                'item' => 'Exchange&diamond'
            )
        ));


        if ($commodityValue > 0) {
            // 价值流转
            StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_FINANCE_TRANS, array(
                'clientData' => array(
                    'tid' => GameConst::ENTITY_ACTION_GET_TOKEN . ':' . $commodityValue . '|',
                    'item' => GameConst::ENTITY_ACTION_CONSUME_MONEY,
                    'value' => abs($goldConfig["price"]),
                    'value2' => $commodityValue,
                )
            ));
        }
        return true;
    }
}